<template>
	<uni-nav-bar fixed="true" statusBar="true" border="false" left-icon="left" title="创建线路" @clickLeft="back"></uni-nav-bar>
	<view class="container pb130 mb60">
		<uni-forms class="form" ref="form" :modelValue="formData" label-width='auto' :rules="rules">
			<uni-forms-item name="linesTitle" required>
				<view class="bg-white is-flex boxsiz mt30 p3020">
					<view class="uni-flex wd100">
						<view>
							<text class="mr50">线路标题</text>
						</view>
						<view class="flex1">
							<input class="uni-input font-28 text-right" maxlength="30" placeholder="请输入线路标题"
								v-model="formData.linesTitle" />
						</view>
						<view class="num">{{formData.linesTitle.length}}/30</view>
					</view>
				</view>
			</uni-forms-item>
			<uni-forms-item name="linesCityDesc" required>
				<view class="bg-white uni-flex w100 mt30 boxsiz p3020">
					<text class="mr50">线路城市</text>
					<view class="uni-flex flex1">
						<picker class="flex1" mode="multiSelector" :range="citys" :range-key="'name'"
							:value="multiIndex" @columnchange="RegionColumnChange"
							@change="RegionChange">
							<view class="picker">
								{{formData.linesCityDesc}}
							</view>
						</picker>
						<uni-icons type="right" color="#999999"></uni-icons>
					</view>
				</view>
			</uni-forms-item>
			<uni-forms-item name="" required>
				<view class="bg-white uni-flex w100 mt30 boxsiz p3020">
						<view><text class="mr50">线路难度</text></view>
						<view class="flex1">
							<uni-rate v-model="formData.linesStar" :max="5" activeColor="#FF9500" />
						</view>
						<view class="num">{{formData.linesStar}}</view>
					</view>
			</uni-forms-item>
			<uni-forms-item required>
				<view class="bg-white p3020 mt30">
					<view class="uni-flex">
						<view class="mr50"><text>图片上传</text></view>
						<view class="color-gray flex1"><uni-icons type="info" size="20"
								color="#888"></uni-icons>第一张图片将同时作为线路封面</view>
						<text class="progress-text">{{ currentUploadIndex }}/{{maxCount}}</text>
					</view>
					<view class="mb20">
						<view class="example-body">
							<view class="image-list">
								<view v-for="(item, index) in imageList" :key="index" class="image-item">
									<image :src="item.path" mode="aspectFill" class="preview-image"></image>
									<view class="progress-overlay" v-if="item.status === 'uploading'">
										<progress :percent="item.progress" stroke-width="3" />
									</view>
									<view class="delete-btn" @tap="deleteImage(index)">×</view>
								</view>
								<!-- 加号上传按钮 -->
								<view class="add-btn" @tap="chooseImage" v-if="imageList.length < maxCount">
									<view class="plus-icon">+</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</uni-forms-item>
			<uni-forms-item name="linesBrief" required>
				<view class="bg-white mt30 mb30 p3020">
					<view class="uni-flex mb25">
						<view class="">
							<text>线路介绍</text>
						</view>
						<view class="num">{{formData.linesBrief.length}}/1000</view>
					</view>
					<view class="is-flex">
						<textarea  style="height: 220px;" maxlength="1000" class="uni-input font-28 text-right w100" placeholder="请输入线路介绍"
							v-model="formData.linesBrief" :adjust-position="true"  @focus="inputBindFocus"  @blur="inputBindBlur" />
					</view>
				</view>
			</uni-forms-item>
		</uni-forms>
		<view class="fixed-bottom-wrap">
			<view class="schdule-card uni-flex">
				<view class="flex-item sign" @click="subForm">
					<text>保存</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import api from '@/common/api/webapi.js'; /*api*/
	import configs from '@/common/api/config.js'; /*api*/
	import storageUtil from '@/common/util/storageUtil.js';
	import OSS from 'ali-oss';
	import Base64 from 'base-64';
	import Md5 from 'js-md5';
	import CryptoJS from 'crypto-js'
	export default {
		data() {
			return {
				imageList: [],
				currentUploadIndex: 0,
				maxCount: 8,
				cityCode:'',
				provinceCode:'',
				multiIndex:[0,0],
				formData: {
					linesTitle: '',
					linesProvinceCode: '',
					linesProvinceDesc: '',
					linesCityCode: '',
					linesCityDesc: '',
					linesStar: 0,
					linesBrief: '',
					coverUrl: '',
					linePicUrl: [],
				},
				bmtime: "",
				jhtime: "",
				startDate: Date.now(),
				endDate: Date.now() + 180 * 24 * 3600 * 1000,
				citys: [
					[],
					[]
				],
				rules: {
					linesTitle: {
						rules: [{
							required: true,
							errorMessage: '请输入线路标题',
						}],
					},
					linesBrief: {
						rules: [{
							required: true,
							errorMessage: '请输入线路介绍',
						}],
					}
				},
				xlnd: 5,
				starValue: 0,
				maxStar: 5,
				customItem: ''
			}
		},
		computed: {

		},
		watch: {},
		onReady() {
			this.$refs.form.setRules(this.rules)
		},
		onShow() {
			// let userLoginFlag = storageUtil.getStorageData("isLogin");
			// if (userLoginFlag) {
			// 	this.getOrders();
			// }
		},
		onLoad(option) {
			let cityStr = storageUtil.getStorageData("region");
			let cityArr = JSON.parse(cityStr);
			Object.entries(cityArr).map(([code, name]) => ({
				code,
				name
			}));
			this.citys[0] = cityArr;
			// console.log("2222", cityArr[0]['code']);
			// this.getCitysList(cityArr[0]['code']);
			this.formData.linesCityDesc = storageUtil.getStorageData("locationCityName");
			this.formData.linesProvinceDesc = storageUtil.getStorageData("locationProvinceName");
			this.getCityCode();
		},
		methods: {
			back(){
				uni.navigateBack();
			},
			inputBindFocus(e) {
				// 获取手机键盘的高度，赋值给input 所在盒子的 bottom 值
				// 注意!!! 这里的 px 至关重要!!! 我搜到的很多解决方案都没有说这里要添加 px
				this.$emit('changeBottomVal' ,  800 +  'px')
			},
			inputBindBlur()  {
			  // input 失去焦点，键盘隐藏，设置 input 所在盒子的 bottom 值为0
			   this.$emit('changeBottomVal', 0)
			}, 
			// 文本框收集换行符
			addNewLine() {
			  this.formData.linesBrief += '\n'; // 添加换行符
			},
			// 集合时间change事件
			changebm: function(e) {
				this.bmtime = e.detail.value;
			},
			// 报名时间change事件
			changejh: function(e) {
				this.jhtime = e.detail.value;
			},
			// 城市选择
			RegionChange(e) {
				let provkey = e.detail.value[0];
				let citykey = e.detail.value[1];
				const citysArray = Array.from(this.citys);
				const provArray = citysArray[0];
				const cityArray = citysArray[1];
				this.formData.linesProvinceDesc = provArray[provkey]['name'];
				this.formData.linesProvinceCode = provArray[provkey]['code'];
				this.formData.linesCityCode = cityArray[citykey]['code'];
				this.formData.linesCityDesc = cityArray[citykey]['name'];
			},
			// 省份列选择事件
			RegionColumnChange(e) {
				if (e.detail.column == 0) {
					let proviceKey = e.detail.value;
					let curProviceCode = this.citys[0][proviceKey];
					this.getCitysList(curProviceCode['code']);
				}
			},
			getCityCode(){
				// 通过当前城市名称获取对应城市的所属省份id和城市id
				api.getCityCode({params:{cityName:this.formData.linesCityDesc}}).then(res => {
					if (res.code === 0) {
						if (res.data) {
							this.provinceCode = res.data.provinceCode;
							this.cityCode = res.data.cityCode;
							this.formData.linesProvinceCode = res.data.provinceCode;
							this.formData.linesCityCode = res.data.cityCode;
							this.getCitysList(this.provinceCode);
						}
					}
				}).catch(e => {
					console.error('获取省份列表失败:', e);
				});
			},
			getCitysList(pid) {
				api.getCitysList({
					params: {
						code: pid
					}
				}).then(res => {
					if (res.code === 0) {
						if (res.data.length > 0) {
							let datas = res.data;
							this.citys[1] = res.data;
							console.log(this.provinceCode,this.cityCode);
							let provicekey = this.citys[0].findIndex(item => item.code === this.provinceCode);
							let citykey = this.citys[1].findIndex(item => item.code === this.cityCode);
							console.log("provicekey",provicekey);
							console.log("citykey",citykey);
							this.multiIndex = [provicekey,citykey];
						}
					} else {}
				}).catch()
			},
			// 调起选择图片
			chooseImage() {
				uni.chooseImage({
					count: this.maxCount - this.imageList.length,
					sizeType: ['original', 'compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						console.log("image1111", res);
						// 确保tempFilePaths存在且是数组
						if (res.tempFiles && Array.isArray(res.tempFiles)) {
							// 初始化文件状态为waiting
							const newFiles = res.tempFiles.map(file => ({
								path: file.path,
								size: file.size,
								status: 'waiting', // 初始状态
								progress: 0,
								base64Data: null
							}))
							this.imageList = [...this.imageList, ...newFiles]
							console.log("this.imageList", this.imageList);
							console.log(typeof(this.imageList[0]['path']));
							this.uploadImages();
						}
					},
					fail: (err) => {
						console.error('选择图片失败:', err)
					}
				})
			},
			// 上传图片
			uploadImages() {
				this.imageList.forEach((item, index) => {
					if (item.status === 'waiting') {
						this.currentUploadIndex = index + 1;
						this.uploadSingleImage(item, index)
					}
				})
			},
			// 上传到oss服务器
			uploadSingleImage(item, index) {
				item.status = 'uploading';
				// 先读取文件为base64
				this.readFileAsBase64(item.path).then(base64Data => {
					console.log('读取到的base64数据长度:', base64Data.length);
					api.getOssInfo({
						params: {
							token: storageUtil.getUserData('token')
						}
					}).then(res => {
						if (res.code === 0) {
							// 使用base64数据创建md5
							const fileMd5 = Md5(base64Data);
							let datas = res.data;
							let month = (new Date().getMonth()) + 1;
							month = month < 10 ? "0" + month : month;
							let extname = item.path.split(".")[1];
							let ossRegion = `https://${datas.bucketName}.oss-cn-hangzhou.aliyuncs.com`;
							let key = 
								`${datas.itineraryPrefix}/${new Date().getFullYear()}${month}/${fileMd5}.${extname}`;
							const uploadTask = uni.uploadFile({
								url: ossRegion, //你的接口地址  需修改
								filePath: item.path, //上传返回的文件本地路径
								fileType: 'image', //文件类型 上传图片的话无需动
								name: 'file', //无需修改
								formData: {
									key: key,
									policy: datas.policy,
									OSSAccessKeyId: datas.accessKeyId,
									'x-oss-signature-version': datas.xossSignatureVersion,
									'x-oss-credential': datas.xossCredential,
									'x-oss-date': datas.xossDate,
									'x-oss-signature': datas.signature,
									'x-oss-security-token': datas.securityToken,
									success_action_status: '200'
								},
								header: {
									'Content-Type': 'application/json' // 根据服务器响应类型设置
								},
								success: (res) => {
									if (res.statusCode == 200) {
										item.status = 'success';
										item.path = `${ossRegion}/${key}`;
										console.log('上传成功:', item.path);
									}
								},
								fail: (err) => {
									item.status = 'fail';
									console.error('上传失败:', err)
								}
							});
							// 监听上传进度
							uploadTask.onProgressUpdate((res) => {
								console.log('上传进度:', res.progress + '%');
								item.progress = Math.floor(res.progress * 100);
							});
						} else {
							console.error('获取OSS信息失败:', res)
						}
					}).catch(error => {
						console.error('API请求失败:', error);
						item.status = 'fail';
					})
				}).catch(error => {
					console.error('读取文件为base64失败:', error);
					item.status = 'fail';
				})
			},
			// 读取文件为base64
			readFileAsBase64(filePath) {
				return new Promise((resolve, reject) => {
					uni.getFileSystemManager().readFile({
						filePath: filePath,
						encoding: 'base64',
						success: (res) => {
							console.log("读取文件成功", res.data.length);
							resolve(res.data);
						},
						fail: (err) => {
							console.error('读取文件失败:', err);
							reject(err);
						}
					});
				});
			},
			deleteImage(index) {
				this.imageList.splice(index, 1);
				this.currentUploadIndex = this.currentUploadIndex - 1;
			},
			// 页面跳转
			navgetTo(page, param, type) {
				if (param != undefined) {
					type = type || '';
					let data = {
						data: param,
						page: type
					}
					uni.navigateTo({
						url: "/" + page + "?param=" + encodeURI(JSON.stringify(data))
					});
				} else {
					uni.navigateTo({
						url: "/" + page
					});
				}
			},
			subForm() {
				// 检查是否有图片正在上传中
				const uploadingImages = this.imageList.filter(item => item.status === 'uploading');
				if (uploadingImages.length > 0) {
					uni.showToast({
						title: '图片上传中，请稍候',
						icon: 'none'
					});
					return;
				}
				
				// 检查是否有图片上传失败
				const failedImages = this.imageList.filter(item => item.status === 'fail');
				if (failedImages.length > 0) {
					uni.showToast({
						title: '部分图片上传失败，请重新上传',
						icon: 'none'
					});
					return;
				}
				
				// 只添加上传成功的图片
				this.formData.linePicUrl = [];
				this.imageList.forEach((item, index) => {
					if (item.status === 'success') {
						this.formData.linePicUrl.push(item.path);
					}
				});
				
				// 检查是否有上传成功的图片
				if (this.formData.linePicUrl.length === 0) {
					uni.showToast({
						title: '请至少上传一张图片',
						icon: 'none'
					});
					return;
				}
				
				// 设置封面图为第一张上传成功的图片
				this.formData.coverUrl = this.formData.linePicUrl[0];
				
				api.createLines(this.formData).then(res => {
					if (res.code === 0) {
						uni.navigateTo({
							url: '/pages/my/select_root'
						})
					} else {
						console.error('创建线路失败:', res);
						uni.showToast({
							title: res.msg || '创建线路失败',
							icon: 'none'
						});
					}
				}).catch(error => {
					console.error('API请求失败:', error);
					uni.showToast({
						title: '网络异常，请重试',
						icon: 'none'
					});
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.container{
		background-color: #f8f8f8;
	}
	.container {
		font-size: 14px;
		line-height: 24px;
	}

	.index-swiper {
		width: 100%;
		height: 670rpx;
	}

	.index-swiper image {
		width: 100%;
		height: 100%;
		object-fit: contain;
	}

	.bottom-wrap {
		position: relative;
		top: -60rpx;
	}

	.wd100 {
		width: 100%;
	}

	.wd55 {
		width: 55%;
	}

	.wd70 {
		width: 70%;
	}

	.flexauto {
		flex: 0 0 auto;
	}

	.schduleForm {
		.is-bt {
			position: relative;
			margin-right: 15px;
		}

		.is-bt::after {
			content: "*";
			position: absolute;
			right: 0;
			color: $uni-text-color-red;
		}
	}

	.is-flex {
		display: flex;
		align-items: center;
	}
	

	.xf-wrap {
		position: relative;
		top: -60rpx;
		overflow: hidden;
	}

	.box-shadow {
		box-shadow: 2rpx 2px 2rpx $uni-text-color-grey8;
		background-color: #ffffff;
		border-radius: 20rpx;
	}

	.xf-wrap input {
		font-weight: bold;
	}

	.uni-flex {
		display: flex;
		align-items: flex-start;
		justify-content: space-between;
	}

	.uni-row {
		flex-direction: row;
	}

	.xc-desc {
		text {
			margin-bottom: 30rpx;
			display: block;
		}
	}

	.pb130 {
		padding-bottom: calc(300px + max(env(safe-area-inset-bottom),20px));
	}

	.share-reward {
		.color-black {
			display: block;
			margin-bottom: 20rpx;
		}

		.is-flex {
			align-items: flex-start;
		}

		.color-gray {
			line-height: 1.8;
			text-align: justify;
			margin-left: 20rpx;
		}
	}

	.fixed-bottom-wrap {
		position: fixed;
		z-index: 111;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #fff;
		width: 100%;
		height: calc(60rpx + max(env(safe-area-inset-bottom),20px));
		line-height: calc(60rpx + max(env(safe-area-inset-bottom),20px));
	}

	.schdule-card {
		height: calc(60rpx + max(env(safe-area-inset-bottom),20px));
		line-height: 60rpx;
		border-top: 1px solid #f8f8f8;
		padding-bottom: max(env(safe-area-inset-bottom),20px);

		.flex-item {
			padding-top: 10rpx;
			width: 25%;
			text-align: center;
			line-height: 40rpx;
		}

		.flex-item:last-child {
			width: 100%;
			padding-top: 0;
		}

		text {
			display: block;
		}

		.sign {
			height: 100%;
			color: $uni-text-color-white;
			background-color: $uni-text-color-green;
			font-size: 32rpx;
			line-height: 100%;

			text {
				line-height: 100rpx;
			}
		}
	}
</style>